import 'fetch-jsonp-polyfill'

function serialize(obj, prefix) {
  var str = [];
  for (var p in obj) {
    var value = obj[p];
    if (obj.hasOwnProperty(p) && (value !== null && value !== undefined)) {
      var k = prefix ? prefix + "[" + p + "]" : p;
      str.push(typeof value == "object" ?
        serialize(value, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(value));
    }
  }
  return str.join("&");
}

export function get(url, data = {}, config = {}) {
  if(data instanceof Object && Object.keys(data).length) {
    url = url + '?' + serialize(data)
  }
  return Promise.resolve(fetch(url, {
    headers: {
      'Accept': 'application/json'
    },
    method: 'GET',
    mode: config.mode || 'cors'
  }));
}

export function jsonp(url, data = {}, config = {}) {
  if(data instanceof Object && Object.keys(data).length) {
    url = url + '?' + serialize(data)
  }
  return Promise.resolve(fetch(url, {
    method: 'JSONP',
    callback: 'callback',
  }));
}

export function post(url, data = {}, config = {}) {
  return Promise.resolve(fetch(url, {
    headers: {
      'Accept': 'application/json, text/javascript, */*',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    // credentials: config.credentials || 'include',
    mode: config.mode || 'cors',
    method: 'POST',
    body: serialize(data)
  }));
}

export function form(url, data, config = {}) {
  var form_data = new FormData();
  Object.keys(data).map(function (key) {
    var value = data[key];
    if (value !== null && value !== undefined) {
      form_data.append(key, value);
    }
  });
  if (config.xhr) {
    return new Promise(function (res, rej) {
      var xhr = new XMLHttpRequest();
      xhr.open('POST', url, true);
      xhr.upload.onprogress = function (event) {
        config.progress && config.progress(event);
      };
      xhr.onload = function (event) {
        res(JSON.parse(event.target.responseText));
      };
      xhr.onerror = function (event) {
        rej(event);
      };
      xhr.send(form_data);
    });
  }
  return Promise.resolve(fetch(url, {
    method: 'POST',
    body: form_data
  }));
}

export default {
  get,
  post,
  form,
  jsonp
};
